-module(db_audio).
-export([insert/4, get_with_offset/3, get_by_language/1, delete/1, delete_all/0]).
-include("records.hrl").


% Insert a audio in the audio table
insert(User, Text, FileName, Language) ->
	A = #audio {
		user = User,
		name = FileName,
		text = Text,
		language = Language
	},
	Fun = fun() ->
		Audio = case mnesia:last(audio) of
			'$end_of_table' ->
				A#audio{id = 0};
			LastId ->
				A#audio{id = LastId + 1}
		end,
		mnesia:write(Audio)
	end,
	mnesia:transaction(Fun).



% Get a list between [offset, offset+5] of the homework IDs that the Student has finished
get_with_offset(Offset, Total, Language) ->
	if Total =:= 0 ->
		{atomic, []};
	true -> 
		Audio = #audio {
			id = '_',
			user = '_',
			name = '_',
			text = '_',
			language = Language
		},
		Fun = fun() ->
					Substract = Total - Offset,
					if 
						Offset > 9 ->
							{_, PreviousCont} = mnesia:select (audio, [{Audio, [], ['$_']}], 5, read),
							AuxList = create_list( (Offset div 5)-1 , []),
							LastCont = lists:foldl(fun(_,Cont) -> {_,NextCont} = mnesia:select(Cont), NextCont end, PreviousCont, AuxList),
							if
								Substract < 5 ->
									Aux = element(6, LastCont),
									Aux2 = setelement(4, Aux, Substract),
									ModifiedCont = setelement(6, LastCont, Aux2),
									mnesia:select(ModifiedCont);
								true -> 
									mnesia:select(LastCont)
							end;
						Offset > 4 ->
							{_, PreviousCont} = mnesia:select (audio, [{Audio, [], ['$_']}], 5, read),
							if
								Substract < 5 ->
									Aux = element(6, PreviousCont),
									Aux2 = setelement(4, Aux, Substract),
									ModifiedCont = setelement(6, PreviousCont, Aux2),
									mnesia:select(ModifiedCont);
								true -> 
									mnesia:select(PreviousCont)
							end;
						true ->
							if
								Substract < 5 ->
									mnesia:select (audio, [{Audio, [], ['$_']}], Substract, read);
								true ->
									mnesia:select (audio, [{Audio, [], ['$_']}], 5, read)
							end
					end
		end,

		{atomic, Results} = mnesia:transaction(Fun),
		case Results of
			'$end_of_table' ->
				[];
			{R, _} ->
				R
		end
	end.


create_list(0, L) -> L;
create_list(I, L) -> create_list(I-1, [I|L]).

	
get_by_language(Language) ->
	Fun = fun() ->
		mnesia:index_read(audio, Language, language)
	end,
	mnesia:transaction(Fun).

delete(Id) ->
	Fun = fun() ->
		[A] = mnesia:read(audio, Id),
		mnesia:delete_object(A)
	end,
	mnesia:transaction(Fun).
	

% Delete all rows
delete_all() ->
	Fun = fun() ->
		Res = mnesia:select(audio, [{mnesia:table_info(audio, wild_pattern), [], ['$_']}]),
		lists:map(fun(X) -> mnesia:delete_object(X) end, Res)
	end,
	mnesia:transaction(Fun).
